<template>
  <el-card shadow="never">
    <el-form ref="formRef" v-loading="loading" :model="detailInfo" :rules="rules">
      <el-form-item style="padding-top: 10px">
        <el-button type="primary" @click="handleAddIndustryType">新增限额</el-button>
        <el-button type="primary" @click="handleSubmit">提交保存</el-button>
      </el-form-item>
      <el-table
        v-loading="loading"
        :span-method="objectSpanMethod"
        :data="detailInfo.tableList"
        highlight-current-row
        default-expand-all
        border
      >
        <el-table-column label="行业分类" align="center" prop="industryType" :min-width="200">
          <template #default="{ row }">
            <el-form-item v-if="!row.isChild" :rules="rules.industryType">
              <el-select v-model="row.industryType" placeholder="请选择" clearable>
                <el-option v-for="item in industryTypes" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <span v-if="row.isChild"></span>
          </template>
        </el-table-column>
        <el-table-column label="选择工种" align="center" prop="workType" :min-width="200">
          <template #default="{ row }">
            <el-form-item :rules="rules.workType">
              <el-select v-model="row.workType" placeholder="请选择" clearable>
                <el-option
                  v-for="item in projectGropuMemberTypeWorks"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="按月限制金额" align="center" prop="monthlyLimit" :min-width="200">
          <template #default="{ row, $index }">
            <el-form-item :prop="`tableList[${$index}]['monthlyLimit']`" :rules="rules.monthlyLimit">
              <el-input v-model="row.monthlyLimit" type="number" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="按日限制金额" align="center" prop="dailyLimit" :min-width="200">
          <template #default="{ row, $index }">
            <el-form-item :prop="`tableList[${$index}]['dailyLimit']`" :rules="rules.dailyLimit">
              <el-input v-model="row.dailyLimit" type="number" />
            </el-form-item>
          </template>
        </el-table-column>
        <!-- <el-table-column label="账户余额安全比例%" align="center" prop="balanceRatio" :min-width="200">
          <template #default="{ row, $index }">
            <el-form-item :prop="`tableList[${$index}]['balanceRatio']`" :rules="rules.balanceRatio">
              <el-input v-model="row.balanceRatio" type="number">
                <template #append>%</template>
              </el-input>
            </el-form-item>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" fixed="right" align="center" width="180">
          <template #default="{ row, $index }">
            <el-button
              v-if="detailInfo.tableList.findLastIndex((i) => i.symbol == row.symbol) == $index"
              type="primary"
              size="small"
              @click="handleAddWorkType(row, $index)"
            >
              增加工种
            </el-button>
            <el-button type="primary" size="small" @click="handleDelete(row, $index)"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from "vue";
import { getPayrollSetting, setPayrollSetting } from "@/api/system/configuration/index";
import { PayrollSettigForm } from "@/api/system/configuration/types";
import { getDicts } from "@/store/modules/dict";
import type { TableColumnCtx, FormRules } from "element-plus";

const industryTypes = getDicts("industryTypes");
const projectGropuMemberTypeWorks = getDicts("projectGropuMemberTypeWork");

const formRef = ref();
const loading = ref(false);
const detailInfo = ref({
  tableList: new Array<PayrollSettigForm>(),
});
const rules = reactive<FormRules<PayrollSettigForm>>({
  balanceRatio: [
    { required: true, message: "账户余额安全比例不能为空", trigger: "change" },
    {
      trigger: "change",
      validator: (rule: any, value: any, callback: any) => {
        if (value > 100 || value < 0) {
          callback(new Error("百分比值必须在0-100之间"));
        } else {
          callback();
        }
      },
    },
  ],
  dailyLimit: [
    { required: true, message: "按日限制金额不能为空", trigger: "change" },
    {
      trigger: "change",
      validator: (rule: any, value: any, callback: any) => {
        if (value > 10000000000 || value < 0) {
          callback(new Error("金额值必须在0-100亿之间"));
        } else {
          callback();
        }
      },
    },
  ],
  monthlyLimit: [
    { required: true, message: "按月限制金额不能为空", trigger: "change" },
    {
      trigger: "change",
      validator: (rule: any, value: any, callback: any) => {
        if (value > 10000000000 || value < 0) {
          callback(new Error("金额值必须在0-100亿之间"));
        } else {
          callback();
        }
      },
    },
  ],
});
const handleAddIndustryType = () => {
  detailInfo.value.tableList.push({
    isChild: false,
    symbol: Symbol(),
    industryType: undefined,
    workType: undefined,
    monthlyLimit: undefined,
    dailyLimit: undefined,
    balanceRatio: undefined,
  });
};

const handleAddWorkType = (row: PayrollSettigForm, index: number) => {
  if (index == detailInfo.value.tableList.length - 1) {
    detailInfo.value.tableList.push({ industryType: row.industryType, isChild: true, symbol: row.symbol });
  } else {
    detailInfo.value.tableList.splice(index + 1, 0, {
      industryType: row.industryType,
      isChild: true,
      symbol: row.symbol,
      workType: undefined,
      monthlyLimit: undefined,
      dailyLimit: undefined,
      balanceRatio: undefined,
    });
  }
};

const handleDelete = (row: PayrollSettigForm, index: number) => {
  if (!row.isChild) {
    ElMessageBox.confirm("该行业分类下所有配置将被删除", "提示", {
      type: "warning",
      confirmButtonText: "确定",
      cancelButtonText: "取消",
    }).then((result) => {
      detailInfo.value.tableList = detailInfo.value.tableList.filter((item) => item.industryType != row.industryType);
    });
  } else {
    detailInfo.value.tableList.splice(index, 1);
  }
};

//表格合并
const objectSpanMethod = (data: {
  row: PayrollSettigForm;
  column: TableColumnCtx<PayrollSettigForm>;
  rowIndex: number;
  columnIndex: number;
}) => {
  let num = 1;
  if (data.columnIndex === 0 && data.row.isChild) {
    num = recursionRowSpan(data.row, data.rowIndex, "symbol", detailInfo.value.tableList);
    return {
      rowspan: num,
      colspan: 1,
    };
  }
  return {
    rowspan: 1,
    colspan: 1,
  };
};
let nowRowSpan = 1;
//判断合并行数
const recursionRowSpan = (row: PayrollSettigForm, rowIndex: number, str: string, data: PayrollSettigForm[]): number => {
  let num: number = 0;
  // 判断上一行字段的值与改行值是否一致
  if (
    nowRowSpan == 1 &&
    rowIndex > 0 &&
    row[str] == data[rowIndex - 1][str] &&
    row.isChild &&
    data[rowIndex - 1].isChild
  ) {
    return 0;
  }
  // 判断下一行字段的值与改行值是否一致
  if (rowIndex + 1 < data.length && row[str] == data[rowIndex + 1][str] && row.isChild && data[rowIndex + 1].isChild) {
    nowRowSpan++;
    num = rowIndex + 1;
    return recursionRowSpan(data[num], num, str, data);
  } else {
    num = nowRowSpan;
    nowRowSpan = 1;
    return num;
  }
};

onMounted(() => {
  handleQuery();
});

//查询
function handleQuery() {
  loading.value = true;
  getPayrollSetting()
    .then((res) => {
      if (res.success) {
        detailInfo.value.tableList = new Array<PayrollSettigForm>();
        res.data = res.data.sort((a: any, b: any) => a.id - b.id);
        res.data.forEach((item: any) => {
          if (detailInfo.value.tableList.findIndex((i) => i.industryType == item.industryType) > -1) {
            detailInfo.value.tableList.push(Object.assign({ symbol: Symbol(), isChild: true }, item));
          } else {
            detailInfo.value.tableList.push(Object.assign({ symbol: Symbol(), isChild: false }, item));
          }
        });
      }
    })
    .finally(() => {
      loading.value = false;
    });
}

//提交保存
const handleSubmit = async () => {
  if (detailInfo.value.tableList.length == 0) return;
  let valid = await formRef.value.validate().catch((e: any) => {
    console.log(e);
  });
  if (valid) {
    loading.value = true;
    let temps = new Array<PayrollSettigForm>();
    for (let i = 0; i < detailInfo.value.tableList.length; i++) {
      let temp = Object.assign({}, detailInfo.value.tableList[i]);
      temp.balanceRatio = (temp?.balanceRatio ?? 0) / 100;
      if (temp.workType == "") temp.workType = null;
      temps.push(temp);
    }
    setPayrollSetting(temps)
      .then((data) => {
        if (data.success) {
          ElMessage({
            type: "success",
            message: "修改成功！",
          });
        }
      })
      .finally(() => {
        loading.value = false;
        handleQuery();
      });
  }
};
</script>

<style lang="less" scoped>
:deep(.el-select) {
  width: 100%;
}
:deep(.el-input) {
  width: 100%;
}
</style>
